#!/bin/bash
#获取最初的集群ip和端口

host=$(ps -elf | grep redis | grep cluster | awk '{print $(NF-1)}'  | awk -F : 'NR==1{print $1}' )
port=$(ps -elf | grep redis | grep cluster | awk '{print $(NF-1)}'  | awk -F : 'NR==1{print $2}' )
#生成一个存储ip和端口的文件
filename=file_$(date +%F_%T)
#获取IP和端口并且写入这个文件
timess=$(date +%F_%T)
redis-cli -h $host -p $port cluster nodes | awk '{print $2}' | awk -F @ '{print $1}' | awk -F : '{print $1,$2}' > /demo01/$filename
while read line;do
    redis_host=$(echo "$line" |awk '{print $1}' )
    redis_port=$(echo "$line" | awk '{print $2}'  )
# 检查是否获取到host和port
	if [ -z "$host" ] || [ -z "$port" ]; then
    	echo "错误：无法获取Redis集群的host或port"
    	exit 1
	fi
	echo "----------------------------------------------------------------------------------------------------"
	line=`redis-cli -h $redis_host -p $redis_port info 2>/dev/null`

    version=`echo "$line" | grep "redis_version" | awk -F: '{print $2}' | tr -d '\r'`

    CpuUse=`echo "$line" | grep "used_cpu_sys:" | awk -F: '{print $2}' | tr -d '\r'`

    MemUse=`echo "$line" | grep "used_memory_human:" | awk -F: '{print $2}' | tr -d '\r'`

    nowConnected=`echo "$line" | grep "connected_clients:" | awk -F: '{print $2}' | tr -d '\r'`

    lastAOFSave=`echo "$line" | grep "rdb_last_save_time:" | awk -F: '{print $2}' | tr -d '\r'`

    last_save_time=`date -d @"$lastAOFSave" +%F_%T 2>/dev/null`

    total_net_input_bytes=`echo "$line" | grep "total_net_input_bytes:" | awk -F: '{print $2}' | tr -d '\r'`

    total_net_output_bytes=`echo "$line" | grep "total_net_output_bytes:" | awk -F: '{print $2}' | tr -d '\r'`

    network_traffic="${total_net_output_bytes}/${total_net_input_bytes}"

    rejected_connections=`echo "$line" | grep "rejected_connections:" | awk -F: '{print $2}' | tr -d '\r'`

    echo "时间: ${nowTime} | 版本: ${version} | CPU使用率: ${CpuUse}% | 内存使用率: ${MemUse} | 当前连接数: ${nowConnected} | 最
近一次RDB存储: ${last_save_time} | 网络流量: ${network_traffic} | 被拒绝的连接数: ${rejected_connections} | 当前节点: ${node}" 

	 echo "--------------------------------------------------------------------------------------------------"
done < /demo01/$filename

